const express = require("express");
const router = express.Router();

const { Comment, User, Article } = require("../models");
const { Op } = require("sequelize");
const { success, failure } = require('../utils/responses');

/**
 * 查询评论列表
 * GET /comments
 */
router.get("/", async function (req, res) {
    try {
        const query = req.query;

        // 当前第几页
        const currentPage = Math.abs(Number(query.currentPage)) || 1;

        // 每页多少条数据
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [["id", "DESC"]],
            limit: pageSize,
            offset: offset,
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['id', 'username', 'nickname', 'avatar'],
                }
            ]
        };

        // 如果按文章ID筛选
        if (query.articleId) {
            condition.where = {
                articleId: query.articleId
            };
        }

        const { count, rows } = await Comment.findAndCountAll(condition);
        success(res, "查询评论列表成功", {
            comments: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            },
        });
    } catch (error) {
        failure(res, error);
    }
});

/**
 * post /comments
 * 发表评论
 */
router.post("/", async function (req, res) {
    try {
        const comment = await Comment.create(filterBody(req));
        success(res, "新增评论成功", comment);
    } catch (error) {
        failure(res, error);
    }
});

/**
 * DELETE /comments/:id
 * 删除评论
 */
router.delete("/:id", async function (req, res) {
    try {
        const id = req.params.id;
        const comment = await Comment.findByPk(id);
        if (!comment) {
            return failure(res, "评论不存在");
        }
        await comment.destroy();
        success(res, "删除评论成功");
    } catch (error) {
        failure(res, error);
    }
});

/** 
 * 白名单过滤
*/
function filterBody(req) {
    return {
        content: req.body.content,
        userId: req.body.userId,
        articleId: req.body.articleId,
    };
}
module.exports = router;